package top.hkyzf.study.leetcode.graph;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-1-25 15:51
 */
public class 岛屿数量_200 {
    public int numIslands(char[][] grid) {
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    result++;
                    dfs(grid, i, j);
                }
            }
        }
        return result;
    }

    private void dfs(char[][] grid, int x, int y) {
        if (grid[x][y] == '1') {
            grid[x][y] = '0';
            // 上
            if (x - 1 >= 0) {
                dfs(grid, x - 1, y);
            }
            // 下
            if (x + 1 < grid.length) {
                dfs(grid, x + 1, y);
            }
            // 左
            if (y - 1 >= 0) {
                dfs(grid, x, y - 1);
            }
            // 右
            if (y + 1 < grid[0].length) {
                dfs(grid, x, y + 1);
            }
        }
    }

    @Test
    public void testNumIsland () {
        char[][] grid = {
                {'1','1','0','0','0'},
                {'1','1','0','0','0'},
                {'0','0','1','0','0'},
                {'0','0','0','1','1'}
        };
        /*char[][] grid = {
                {'0', '0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0'},
                {'0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '0', '0', '0'},
                {'0', '1', '1', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0'},
                {'0', '1', '0', '0', '1', '1', '0', '0', '1', '0', '1', '0', '0'},
                {'0', '1', '0', '0', '1', '1', '0', '0', '1', '1', '1', '0', '0'},
                {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0'},
                {'0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0', '0', '0', '1', '1', '0', '0', '0', '0'}
        };*/
        System.out.println(numIslands(grid));
    }
}
